﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;

namespace batchMail
{
    public partial class Form1 : Form
    {


        /// <summary>
        /// 发送邮件的smtp服务
        /// </summary>
        SmtpClient client = null;


        /// <summary>
        /// 选择附件存在的文件夹
        /// </summary>
        private string fileDirectoryPath= "";


        private List<MapEmail> mapEmailList = null;

        private List<SendResult> sendResultList = null;

        private int successCount=0;
        private int failCount = 0;
        private int sendCount = 0;


        private void updateLableCount()
        {
            labelSuccess.Text = $"发送成功: {successCount} 次";
            labelFail.Text = $"发送失败: {failCount} 次";

        }




        public Form1()
        {
            InitializeComponent();
        }

        async private void buttonStart_Click(object sender, EventArgs e)
        {

            initializationControls();

            labelMessage.Text = "正在附件获取文件数量";

            string[] files = null;
            //找文件

            if (!Directory.Exists(fileDirectoryPath))
            {
                labelMessage.Text = "目录地址错误";
                return;
            }

            files = Directory.GetFiles(fileDirectoryPath,"*",SearchOption.AllDirectories);

            if(files.Length<=0)
            {
                labelMessage.Text = "目录下无文件";
                return;
            }


            labelCount.Text = $"文件数量:{files.Length}";


            labelMessage.Text = "正在创建发送邮件的对象";

            client = new SmtpClient();

            client.Host = textBoxSMTP.Text.Trim();

            client.Timeout = 100000;


            string sendEmail = textBoxEmail.Text;


            // FSCRAHHDLBIAOQBI
            client.Credentials = new System.Net.NetworkCredential(sendEmail, textBoxAuthorizationCode.Text);


            MailAddress from = new MailAddress(sendEmail);


            MailAddress to = null;
            MailMessage message = null;

            string title = textBoxTitle.Text;
            string body = textBoxBody.Text;

            mapEmailList = MapEmail.FromTxtToMapEmail();

            SendResult sResult = null;

            sendResultList = new List<SendResult>();

            failCount = 0;
            successCount = 0;


            buttonStart.Enabled = false;

            progressBar1.Value = 0;
            progressBar1.Maximum = files.Length;
            //progressBar1.Visible = true;
            



            foreach (var file in files)
            {
                

                string name = Path.GetFileNameWithoutExtension(file);

                MapEmail[] mapEmails = mapEmailList.FindAll((email) => email.UnitId == name).ToArray();

                

                foreach(var mapEmail in mapEmails)
                {
                    sResult = new SendResult();
                    sResult.IsSuccess = true;
                    sResult.FromEmail = sendEmail;
                    sResult.FilePath = file;
                    sResult.ToEmail = mapEmail.Email;

                    to = new MailAddress(mapEmail.Email);
                    message = new MailMessage(from, to);

                    message.Body = textBoxBody.Text;
                    message.BodyEncoding = Encoding.UTF8;
                    
                    message.Subject = textBoxTitle.Text;
                    message.SubjectEncoding = Encoding.UTF8;

                    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                    message.Attachments.Add(data);

                    labelMessage.Text = $"正在向{mapEmail.Email}发送信息";

                    try
                    {
                        await client.SendMailAsync(message);
                        successCount++;

                    }
                    catch (Exception ex)
                    {
                        sResult.IsSuccess = false;
                        sResult.message = ex.Message;
                        failCount++;
                    }

                    sendResultList.Add(sResult);

                    updateLableCount();

                }


                progressBar1.Value++;

                

            }


            labelMessage.Text = "完成";

            SendResult.SaveLogFile(sendResultList.ToArray());


            buttonStart.Enabled = true;
















            // Clean up.
            // message.Dispose();
        }

       
        private void buttonFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();


            dialog.SelectedPath = fileDirectoryPath;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dialog.SelectedPath;
                fileDirectoryPath = dialog.SelectedPath;
            }

        }



        private void initializationControls()
        {
            //progressBar1.Visible = false;
            buttonStop.Visible = false;

            labelSuccess.Text = "";
            labelFail.Text = "";
            labelCount.Text = "";
            labelMessage.Text = "";
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            initializationControls();
        }
    }
}
